package com.gy.studyonlineapp.fragment;

import static android.content.ContentValues.TAG;

import androidx.lifecycle.ViewModelProvider;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gy.studyonlineapp.R;
import com.gy.studyonlineapp.ViewModel.ViewModelFind;
import com.gy.studyonlineapp.activity.KnowledgeActivity;
import com.gy.studyonlineapp.activity.LoginActivity;
import com.gy.studyonlineapp.activity.MainActivity;
import com.gy.studyonlineapp.adapter.KnowledgeAdapter;
import com.gy.studyonlineapp.common.Constants;
import com.gy.studyonlineapp.constants.LearnCloudClass;
import com.gy.studyonlineapp.constants.SharedPreference;
import com.gy.studyonlineapp.entity.Knowledge;
import com.gy.studyonlineapp.entity.KnowledgeItem;
import com.gy.studyonlineapp.entity.Question;
import com.gy.studyonlineapp.entity.User;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.leancloud.AVObject;
import cn.leancloud.AVQuery;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FragmentFind extends Fragment {

    private ViewModelFind mViewModel;
    private ViewFlipper flipper;
    private Animation[] animation = new Animation[2];
    private int[] images = new int[]{R.drawable.java,R.drawable.android,R.drawable.git,R.drawable.csdn};
    final int FLAG_MSG=0x001;
    private Message message;
    private ListView Lv = null;

    private List<Knowledge> knowledgeList = new ArrayList<Knowledge>();

    public static FragmentFind newInstance() {
        return new FragmentFind();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragement_find,container,false);

        initKnowledge();  // 初始化知识数据
        Lv = view.findViewById(R.id.ListView3);
        Lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView objectId = view.findViewById(R.id.ad_objectId);
                Intent intent = new Intent(getActivity(), KnowledgeActivity.class);
                intent.putExtra("objectId",objectId.getText().toString());
                startActivity(intent);
            }
        });

        // 为搜索功能绑定事件
        ImageView searchBtn = view.findViewById(R.id.select_p01);
        EditText editText = view.findViewById(R.id.select01);
        ImageButton clean = view.findViewById(R.id.select_p02);

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取文本框中的内容
                String title = editText.getText().toString();
                if (!title.isEmpty()) {
                    // 进行查询数据库
                    String url = "http://" + Constants.localhost + ":8080/search-by-title";
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("title", title)
                            .build();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();
                    Call call = client.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {}
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            Gson gson = new Gson();
                            KnowledgeItem knowledgeItem = gson.fromJson(response.body().string(), KnowledgeItem.class);
                            String objectId = knowledgeItem.getId();
                            if (!objectId.isEmpty()) {
                                Intent intent = new Intent(getActivity(), KnowledgeActivity.class);
                                intent.putExtra("objectId",objectId);
                                startActivity(intent);
                            } else {
                                Toast.makeText(getActivity(), "查不到结果,请重新输入标题", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    Toast.makeText(getContext(), "请输入文章标题", Toast.LENGTH_SHORT).show();
                }
            }
        });
        clean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 将EditText内容清空
                editText.setText("");
            }
        });

        //实现图片轮播
        flipper = view.findViewById(R.id.viewFlipper3);
        for (int i = 0; i<images.length;i++){
            ImageView imageView = new ImageView(view.getContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);//调节图片位置
            imageView.setImageResource(images[i]);
            flipper.addView(imageView);
        }
        //动画横移
        animation[0] = AnimationUtils.loadAnimation(view.getContext(),R.anim.right);
        animation[1] = AnimationUtils.loadAnimation(view.getContext(),R.anim.left);
        flipper.setInAnimation(animation[0]);
        flipper.setOutAnimation(animation[1]);

        message = Message.obtain();
        message.what=FLAG_MSG;
        handler.sendMessage(message);
        return view;
    }

    //初始化listView 图片和文本
    private void initKnowledge() {
        List<KnowledgeItem> knowledgeItems = new ArrayList<>();
        String url = "http://" + Constants.localhost + ":8080/search-all-detail";
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                String string = response.body().string();
                List<KnowledgeItem> list = gson.fromJson(string, new TypeToken<List<KnowledgeItem>>() {}.getType());
                if (list != null && list.size() > 0) {
                    for (KnowledgeItem item : list) {
                        knowledgeItems.add(item);
                    }
                    getActivity().runOnUiThread(() -> {
                        Lv.setAdapter(new KnowledgeAdapter(getContext(), R.layout.knowledge_item, knowledgeItems));
                    });
                }
            }
        });
    }
    //定时任务3秒停留图片
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            if(msg.what==FLAG_MSG)
                flipper.showPrevious();
            message=handler.obtainMessage(FLAG_MSG);
            handler.sendMessageDelayed(message,3000);
        }
    };

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(ViewModelFind.class);
        // TODO: Use the ViewModel
    }

}